﻿using System;

namespace Loong.AspNetCore.Models
{
    internal class DefaultErrorInfoConverter : IExceptionToErrorInfoConverter
    {
        public IExceptionToErrorInfoConverter Next { set; private get; }

        public ErrorInfo Convert(Exception exception)
        {
            var errorInfo = CreateErrorInfoWithoutCode(exception);

            if (exception is IHasErrorCode)
            {
                errorInfo.Code = (exception as IHasErrorCode).Code;
            }

            return errorInfo;
        }

        private ErrorInfo CreateErrorInfoWithoutCode(Exception exception)
        {
            return new ErrorInfo(GetExceptionMessage(exception));
        }

        private string GetExceptionMessage(Exception exception)
        {
            if (exception.InnerException != null)
            {
                return GetExceptionMessage(exception.InnerException);
            }

            if (exception is LoongException) return exception.Message;

            return "操作失败，请稍后重试。";
        }
    }
}
